package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

import static java.nio.file.Files.delete;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    private static final String FOLLOW_KEY_PREFIX = "follow:user:";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result follow(Long followId, Boolean isFollow) {
        // 1. 获取当前用户并校验
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Long userId = user.getId();

        // 2. 判断是关注还是取消关注
        String key = FOLLOW_KEY_PREFIX + userId;

        if (Boolean.TRUE.equals(isFollow)) {
            // 关注逻辑
            Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, followId.toString());
            if (Boolean.TRUE.equals(isMember)) {
                return Result.fail("已关注该用户");
            }

            // 原子性操作：先数据库后Redis
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followId);
            if (save(follow)) {
                stringRedisTemplate.opsForSet().add(key, followId.toString());
                return Result.ok();
            }
        } else {
            // 取消关注逻辑
            boolean removed = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId)
                    .eq("follow_user_id", followId));

            if (removed) {
                stringRedisTemplate.opsForSet().remove(key, followId.toString());
                return Result.ok();
            }
        }
        return Result.fail("操作失败");
    }

    @Override
    public Result followOrNot(Long followId) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Long count = query().eq("user_id", user.getId()).eq("follow_user_id", followId).count();
        return Result.ok(count > 0);
    }

    @Override
    public Result followCommons(Long id) {
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(
                FOLLOW_KEY_PREFIX + id,
                FOLLOW_KEY_PREFIX + UserHolder.getUser().getId()
        );
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(0);
        }
        List<UserDTO> users = intersect.stream().map(userId -> {
            UserDTO user = new UserDTO();
            //User user1 = userService.getById(Long.valueOf(userId));
            User user1 = userMapper.selectById(Long.valueOf(userId));
            BeanUtils.copyProperties(user1, user);
            return user;
        }).toList();
        return Result.ok(users);
    }
}
